<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'test:testData:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <div class="basicForm">
      <BasicForm @register="registerForm">
        <!-- 插槽（备注信息） -->
        <template #remarks="{ model, field }">
          <WangEditor
            v-model:value="model[field]"
            :bizKey="record.id"
            :bizType="'testDataChild_' + field"
            :height="300"
          />
        </template>
        <!-- 插槽（子表数据） -->
        <template #testDataChildList>
          <BasicTable
            @register="registerTestDataChildTable"
            @row-click="handleTestDataChildRowClick"
          >
            <template #testDataChildUpload="{ record: childRecord }">
              <BasicUpload
                v-model:value="childRecord.dataMap"
                :bizKey="childRecord.id"
                :bizType="'testDataChild_file'"
                :uploadType="'all'"
                :loadTime="record.__t"
              />
            </template>
          </BasicTable>
          <a-button class="mt-2" @click="handleTestDataChildAdd" v-auth="'test:testData:edit'">
            <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
          </a-button>
        </template>
      </BasicForm>
    </div>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    TestData,
    testDataSave,
    testDataForm,
  } from '/@/api/test/testData';
  import { officeTreeData } from '/@/api/sys/office';
  import { areaTreeData } from '/@/api/sys/area';
  import { BasicUpload } from '/@/components/Upload';
  import { WangEditor } from '/@/components/WangEditor';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const record = ref<TestData>({} as TestData);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数据') : t('编辑数据'),
  }));
  const modifyStyle = () => {
    let el = document.querySelectorAll('.basicForm > form > .ant-row')[0];
    
    inputFormSchemas.forEach((item, index) => {
      if (item.componentProps && (item.componentProps as any).labelColor) {
        (el.children[index].children[0].children[0].children[0] as any).style.color = (
          item.componentProps as any
        ).labelColor;
      }
      if (item.componentProps && (item.componentProps as any).labelWeight) {
        (el.children[index].children[0].children[0].children[0] as any).style.fontWeight = (
          item.componentProps as any
        ).labelWeight;
      }
    });
  };
  let inputFormSchemas: FormSchema[] = [];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120, // 控件前面的标签宽度
    schemas: inputFormSchemas, // 控件定义列表
    baseColProps: { lg: 24, md: 24 }, // 控件默认栅格布局方式（响应式）
  });

  const [registerTestDataChildTable, testDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleTestDataChildDelete.bind(this, record),
          },
          auth: 'test:testData:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    // showTableSetting: true, //是否显示表格右上角3个默认按钮
  });

  async function setTestDataChildTableData(_res: Recordable) {
    testDataChildTable.setColumns([
      {
        title: t('单行文本'),
        dataIndex: 'testInput',
        width: 130,
        align: 'left',
        editRow: true, //编辑行
        editComponent: 'Input', //编辑行类型
        editRule: true,
      },
      {
        title: t('多行文本'),
        dataIndex: 'testTextarea',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
      {
        title: t('下拉框'),
        dataIndex: 'testSelect',
        width: 130,
        align: 'left',
        dictType: 'sys_menu_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_menu_type',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('下拉多选'),
        dataIndex: 'testSelectMultiple',
        width: 130,
        align: 'left',
        dictType: 'sys_menu_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'sys_menu_type',
          mode: 'multiple',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('日期选择'),
        dataIndex: 'testDate',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD',
          showTime: false,
        },
        editRule: false,
      },
      {
        title: t('日期时间'),
        dataIndex: 'testDatetime',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
      },
      {
        title: t('用户选择'),
        dataIndex: 'testUser.userCode',
        dataLabel: 'testUser.userName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: officeTreeData,
          params: { isLoadUser: true, userIdPrefix: '' },
          canSelectParent: false,
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('机构选择'),
        dataIndex: 'testOffice.officeCode',
        dataLabel: 'testOffice.officeName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: officeTreeData,
          canSelectParent: false,
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('区域选择'),
        dataIndex: 'testAreaCode',
        dataLabel: 'testAreaName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          api: areaTreeData,
          canSelectParent: false,
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('文件上传'),
        dataIndex: 'upload',
        width: 160,
        align: 'left',
        slot: 'testDataChildUpload',
      },
    ]);
    testDataChildTable.setTableData(record.value.testDataChildList || []);
  }

  function handleTestDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  // 添加编辑行，可指定初始数据
  function handleTestDataChildAdd() {
    testDataChildTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  // 删除编辑行方法
  function handleTestDataChildDelete(record: Recordable) {
    testDataChildTable.deleteTableDataRecord(record);
  }

  // 获取子表数据（支持返回删除未提交的数据）
  async function getTestDataChildList() {
    let testDataChildListValid = true;
    let testDataChildList: Recordable[] = [];
    for (const record of testDataChildTable.getDataSource()) {
      // 验证控件内容，并取消行的编辑状态（如果验证失败返回false）
      if (!(await record.onEdit?.(false, true))) {
        testDataChildListValid = false;
      }
      testDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of testDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      testDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!testDataChildListValid) {
      throw { errorFields: [{ name: ['testDataChildList'] }] };
    }
    return testDataChildList;
  }

  // 弹窗后的回调事件，进行一些表单数据初始化等操作
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true }); // 显示加载框
    await resetFields(); // 重置表单数据

    const res = await testDataForm(data); // 查询表单数据
    record.value = (res.testData || {}) as TestData;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value); // 设置字段值
    // setTestDataChildTableData(res); // 设置子表数据（没有子表可不写）
    setDrawerProps({ loading: false }); // 隐藏加载框
    modifyStyle();
  });

  async function handleSubmit() {
    try {
      const data = await validate(); // 验证表单，并返回数据
      console.log(data, 'data=====');
      setDrawerProps({ confirmLoading: true }); // 显示提交加载中
      // 设置提交的参数（QueryString，后台 Controller 的 get 接受）
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // 获取并设置子表数据
      data.testDataChildList = await getTestDataChildList();
      // console.log('submit', params, data, record);
      // 将数据提交给后台（如果失败跳转到 catch）
      const res = await testDataSave(params, data);
      showMessage(res.message); // 显示提交结果
      setTimeout(closeDrawer); // 隐藏抽屉弹窗
      emit('success', data); // 触发事件，列表数据刷新
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false }); // 隐藏提交加载中
    }
  }
</script>
<style>
  .col {
    color: red;
    font-weight: 100;
  }
</style>
